package xyz.xtt.exchange.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tongtong.share.response.ImageAuditResponse;
import com.tongtong.share.response.VideoAuditResponse;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import xyz.xtt.exchange.controller.AuditResEnum;
import xyz.xtt.exchange.dto.AssetAuditDto;
import xyz.xtt.exchange.entity.TblAssetAudit;
import xyz.xtt.exchange.mapper.TblAssetAuditMapper;
import xyz.xtt.exchange.service.IInnerService;
import xyz.xtt.exchange.service.ITblAssetAuditService;
import xyz.xtt.exchange.vo.AssetAuditVo;
import xyz.xtt.pay.api.enums.PayOrderBusinessTypeEnum;
import xyz.xtt.pay.api.enums.PayOrderStatusEnum;
import xyz.xtt.pay.client.response.PayOrderResponse;

/**
 * <p>
 * 资产铸造审核表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-02-08
 */
@Service
@Slf4j
public class TblAssetAuditServiceImpl extends ServiceImpl<TblAssetAuditMapper, TblAssetAudit> implements ITblAssetAuditService {

	@Autowired
	private TblAssetAuditMapper tblAssetAuditMapper;

	private static String BenefitRecoverMsg = "视频铸造取消返还";
	@Autowired
	private IInnerService iInnerService;

	/**
	 * 获取我的审核列表
	 * 
	 * @param uid
	 * @return
	 */
	@Override
	public List<AssetAuditVo> getAuditList(Long uid, Integer currentPage, Integer pageSize) {
		String page = String.format("limit %d, %d", ((currentPage - 1) * pageSize), pageSize);

		LambdaQueryWrapper<TblAssetAudit> query = new LambdaQueryWrapper<>();
		query.eq(TblAssetAudit::getAppUserId, uid).orderByDesc(TblAssetAudit::getCreateTime).last(page);
		List<TblAssetAudit> tblAssetAudits = tblAssetAuditMapper.selectList(query);
		List<AssetAuditVo> assetAuditVos = new ArrayList<>();
		for (TblAssetAudit tblAssetAudit : tblAssetAudits) {
			// 审核中， 获取审核结果
			if (Objects.equals(tblAssetAudit.getResult(), AuditResEnum.CHECKING.code())) {
				// 查询审核数据，如果审核有结果， 修改数据
				AuditResEnum result = getAuditByRequestId(tblAssetAudit);
				tblAssetAudit.setResult(result.code());
			}
			Integer payStatus = 0;
			// 审核通过，未取消， 获取支付状态
			if (Objects.equals(tblAssetAudit.getResult(), 1) && Objects.equals(tblAssetAudit.getState(), 0)) {
				PayOrderResponse payOrder = iInnerService
						.infoPayOrderWithBusinessRefId(tblAssetAudit.getId().toString(), PayOrderBusinessTypeEnum.PERSONAL_MINT_V2);
				if (Objects.nonNull(payOrder)) {
					payStatus = payOrder.getPayStatus();
				}
			}
			// 处理数据
			assetAuditVos.add(AssetAuditVo.create(tblAssetAudit, payStatus));
		}
		return assetAuditVos;
	}

	private AuditResEnum getAuditByRequestId(TblAssetAudit tblAssetAudit) {

		// 视频审核
		AuditResEnum status = AuditResEnum.CHECKING;
		if (StringUtils.hasLength(tblAssetAudit.getVideoPath())) {
			status = getAndSetVideoResult(tblAssetAudit);
		} else if (StringUtils.hasLength(tblAssetAudit.getFileList())) {
			status = getImageListAudit(tblAssetAudit);
		}

		// 如果查询结果， 修改查询结果
		if (!Objects.equals(status, AuditResEnum.CHECKING) && Objects.nonNull(status)) {
			setAssetAuditResult(tblAssetAudit.getId(), status.code());
		}
		return status;
	}

	private AuditResEnum getImageListAudit(TblAssetAudit tblAssetAudit) {
		if (!StringUtils.hasLength(tblAssetAudit.getFileList())) {
			return AuditResEnum.CHECKING;
		}
		// 查询结果
		List<ImageAuditResponse> listApiResult = iInnerService.describeAuditingImageRequestId(tblAssetAudit.getVideoAuditRequestId());
		log.info("图片列表查询审核结果: requestId:{}, result:{} ", tblAssetAudit.getVideoAuditRequestId(), JSONUtil.toJsonStr(listApiResult));
		// 没有审核结果
		if (Objects.isNull(listApiResult)) {
			return AuditResEnum.CHECKING;
		}
		// 查询审核结果
		for (ImageAuditResponse item : listApiResult) {
			if (!item.isCheck()) {
				return AuditResEnum.CHECKING;
			}
			if (item.getState().equals("Failed")) {
				return AuditResEnum.FAIL;
			}
		}
		return AuditResEnum.SUCCESS;
	}

	@Override
	public TblAssetAudit assetAuditInfo(Long assetAuditId) {
		TblAssetAudit tblAssetAudit = tblAssetAuditMapper.selectById(assetAuditId);
		return tblAssetAudit;
	}

	@Override
	public AssetAuditDto getAuditRecord(Long uid, Long auditId) {
		LambdaQueryChainWrapper<TblAssetAudit> query = this.lambdaQuery();
		TblAssetAudit assetAudit = query.eq(TblAssetAudit::getAppUserId, uid).eq(TblAssetAudit::getId, auditId).one();
		return convertAssetAuditDto(assetAudit);
	}

	/**
	 * 根据审核ID 查询支付状态
	 *
	 * @param auditId
	 * @return
	 */
	private AssetAuditDto convertAssetAuditDto(TblAssetAudit assetAudit) {
		if (assetAudit == null) {
			return null;
		}
		AssetAuditDto assetAuditDto = new AssetAuditDto();
		BeanUtils.copyProperties(assetAudit, assetAuditDto);
		return assetAuditDto;
	}

	/**
	 * 视频审核结果
	 * 
	 * @param tblAssetAudit
	 * @return
	 */
	private AuditResEnum getAndSetVideoResult(TblAssetAudit tblAssetAudit) {
		if (StringUtils.hasLength(tblAssetAudit.getVideoAuditRequestId())) {
			return AuditResEnum.CHECKING;
		}
		VideoAuditResponse data = iInnerService.receiveVideoAuditing(tblAssetAudit.getVideoAuditRequestId());
		// 查询失败
		if (Objects.isNull(data)) {
			return AuditResEnum.CHECKING;
		}
		// 审核结果 审核中
		if (data.isCheck()) {
			return AuditResEnum.CHECKING;
		}
		if (data.getState().equals("Failed")) {
			return AuditResEnum.FAIL;
		}
		return AuditResEnum.SUCCESS;
	}

	/**
	 * 修改状态
	 * 
	 * @param id
	 * @param result
	 */
	private void setAssetAuditResult(Long id, Integer result) {
		LambdaUpdateWrapper<TblAssetAudit> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(TblAssetAudit::getId, id).set(TblAssetAudit::getResult, result);
		baseMapper.update(updateWrapper);
	}

//	/**
//	 * 根据审核ID 查询支付状态
//	 *
//	 * @param auditId
//	 * @return
//	 */
//	public PayOrder getPayOrderByAuditId(String auditId) {
//		LambdaQueryWrapper<PayOrder> query = new LambdaQueryWrapper<>();
//		query.eq(PayOrder::getBusinessRefId, auditId).eq(PayOrder::getBusinessType, PayOrderBusinessTypeEnum.PERSONAL_MINT_V2.getCode());
//		return payOrderMapper.selectOne(query);
//	}

	@Override
	public Boolean setAssetAuditStatus(Long uid, Long id, Integer status) {
		TblAssetAudit tblAssetAudit = tblAssetAuditMapper.selectById(id);
		// 不存在
		if (Objects.isNull(tblAssetAudit)) {
			return false;
		}
		// 不是自己的
		if (!Objects.equals(tblAssetAudit.getAppUserId(), uid)) {
			return false;
		}

		// 判断 已经铸造
		if (Objects.isNull(tblAssetAudit.getAssetId()) || tblAssetAudit.getAssetId() > 0 || !tblAssetAudit.getState().equals(0)) {
			return false;
		}
		PayOrderResponse payOrder = iInnerService.queryPayStatus(tblAssetAudit.getId(), PayOrderBusinessTypeEnum.PERSONAL_MINT_V2.getCode());
		// 查询支付状态
//		PayOrder payOrder = getPayOrderByAuditId(tblAssetAudit.getId().toString());
		// 有订单的情况
		if (Objects.nonNull(payOrder)) {
			// 支付成功 或者 支付中，不支持退款
			if (payOrder.getPayStatus().equals(PayOrderStatusEnum.PAY_SUCCESS.getCode())
					|| payOrder.getPayStatus().equals(PayOrderStatusEnum.PAYING.getCode())) {
				return false;
			}
		}

		// 返回免费次数
		if (tblAssetAudit.getRightAmount() > 0) {
			iInnerService.userBenefitRecover(uid, tblAssetAudit.getId(), BenefitRecoverMsg);
		}
		// 修改状态
		setAssetAudit(id, status);
		return true;
	}

	private void setAssetAudit(Long id, Integer status) {
		LambdaUpdateWrapper<TblAssetAudit> updateWrapper = new LambdaUpdateWrapper<>();
		updateWrapper.eq(TblAssetAudit::getId, id).set(TblAssetAudit::getState, status);
		baseMapper.update(updateWrapper);
	}

	@Override
	public boolean failReMint(Long id, String videoPath, String imgPath, String assetName, String description) {
		LambdaUpdateChainWrapper<TblAssetAudit> update = new LambdaUpdateChainWrapper<>(baseMapper);
		return update
				.eq(TblAssetAudit::getId, id)
				.set(TblAssetAudit::getVideoPath, videoPath)
				.set(TblAssetAudit::getImgPath, imgPath)
				.set(TblAssetAudit::getDescription, description)
				.update();
	}

	@Override
	public TblAssetAudit failInfo(Long uid, Long id) {
		LambdaQueryChainWrapper<TblAssetAudit> query = new LambdaQueryChainWrapper<>(baseMapper);
		return query.eq(TblAssetAudit::getId, id).eq(TblAssetAudit::getResult, 2).one();
	}

	@Override
	public Boolean assetAuditPayMint(Long assetAuditId, Long assetId) {
		LambdaUpdateChainWrapper<TblAssetAudit> update = new LambdaUpdateChainWrapper<TblAssetAudit>(this.baseMapper);
		return update.eq(TblAssetAudit::getId, assetAuditId).set(TblAssetAudit::getAssetId, assetId).update();
	}

}
